package com.hsy.linemoney.modules.auth.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.deparse.dpframe.tools.utils.DPGsonUtil;
import com.deparse.dpframe.tools.utils.DPLogUtil;
import com.hsy.linemoney.R;
import com.hsy.linemoney.apiservice.AddReferenceId;
import com.hsy.linemoney.apiservice.Callback;
import com.hsy.linemoney.apiservice.CurrencyService;
import com.hsy.linemoney.apiservice.IsTermsOfUseCompleteService;
import com.hsy.linemoney.apiservice.LineMoneyContext;
import com.hsy.linemoney.apiservice.ServiceTypeService;
import com.hsy.linemoney.apiservice.SignUpService;
import com.hsy.linemoney.beans.User;
import com.hsy.linemoney.common.PasswordSaver;
import com.hsy.linemoney.modules.auth.activity.AgreementActivity;
import com.hsy.linemoney.modules.auth.activity.LoginActivity;
import com.hsy.linemoney.modules.auth.activity.VerifyEmailActivity;
import com.hsy.linemoney.modules.common.CommonBaseFragment;
import com.hsy.linemoney.modules.main.MainActivity;
import com.liferay.mobile.android.auth.Authentication;
import com.liferay.mobile.android.auth.SignInMethod;
import com.liferay.mobile.android.auth.basic.BasicAuthentication;
import com.liferay.mobile.android.callback.typed.JSONObjectCallback;
import com.liferay.mobile.android.service.Session;
import com.liferay.mobile.android.service.SessionImpl;
import com.liferay.mobile.android.v7.user.UserService;

import org.json.JSONObject;

/**
 * Created by Administrator on 2016/7/6.
 */
public class SignUpFragment extends CommonBaseFragment {
    private TextView user_type_spinner;
    private EditText name, password_edit, password_edit_again, email, tui_jian;
    private String[] userTypes = {"普通汇款用户", "LineMoney Agent 代理"};
    private boolean isHidden = true;
    private LinearLayout password_image;
    private String type = userTypes[0];
    private TextView commit;
    private Callback<CurrencyService.CurrencyListResult> currencyListResultCallback = new Callback<CurrencyService.CurrencyListResult>() {
        @Override
        public void onSuccess(int what, CurrencyService.CurrencyListResult result) {
            new ServiceTypeService().getServiceTypeList(serviceTypeListResultCallback);
        }

        @Override
        public void onError(int what, int type, String msg, Exception e) {
            new ServiceTypeService().getServiceTypeList(serviceTypeListResultCallback);
        }
    };

    private Callback<ServiceTypeService.ServiceTypeListResult> serviceTypeListResultCallback = new Callback<ServiceTypeService.ServiceTypeListResult>() {
        @Override
        public void onSuccess(int what, ServiceTypeService.ServiceTypeListResult result) {
            startActivity(VerifyEmailActivity.class);
            showToast(R.string.txt_sign_up_successfully);
            hideProgressDialog();
        }

        @Override
        public void onError(int what, int type, String msg, Exception e) {
            startActivity(VerifyEmailActivity.class);
            showToast(R.string.txt_sign_up_successfully);
            hideProgressDialog();
        }
    };

    @Override
    protected int getFragmentLayout() {
        return R.layout.fragment_sign_up;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        user_type_spinner = F(R.id.user_type_spinner);

        name = F(R.id.name);

        password_edit = F(R.id.password_edit);

        password_edit_again = F(R.id.password_edit_again);

        email = F(R.id.email);
        tui_jian = F(R.id.tui_jian);

        user_type_spinner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog();
            }
        });

        password_image = F(R.id.password_image);
        password_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                password_edit.setTransformationMethod(isHidden ? HideReturnsTransformationMethod.getInstance() : PasswordTransformationMethod.getInstance());
                isHidden = !isHidden;
            }
        });

        commit = F(R.id.commit);
        commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkSignUp()) {
//                    startActivity(AgreementActivity.class,password_edit.getText().toString(),password_edit_again.getText().toString(),email.getText().toString(),name.getText().toString(),type, TextUtils.isEmpty(tui_jian.getText().toString()) ? null : tui_jian.getText().toString());
                    showProgressDialog(getAttchedActivity());
                    new SignUpService().signUp(
                            20155,//companyId
                            false,//autoPassword
                            password_edit.getText().toString(),//password1
                            password_edit_again.getText().toString(),//password2
                            true,//autoScreenName
                            "",//screenName
                            email.getText().toString(),//emailAddress
                            -1,//facebookId
                            "",//openId
                            LineMoneyContext.getLocalLanguagePair().locale.getLanguage(),//locale
                            name.getText().toString(),//firstName
                            "",//middleName
                            "",//lastName
                            -1,//prefixId
                            -1,//suffixId
                            true,//male
                            8,//birthdayMonth
                            11,//birthdayDay
                            1988,//birthdayYear
                            type,//jobTitle
                            null,//groupIds
                            null,//organizationIds
                            null,//roleIds
                            null,//userGroupIds
                            null,//addresses
                            null,//emailAddresses
                            null,//phones
                            null,//websites
                            null,//announcementsDelivers
                            true,//sendEmail,
                            new Callback<SignUpService.SignUpResult>() {

                                @Override
                                public void onSuccess(int what, SignUpService.SignUpResult result) {
                                    if (!TextUtils.isEmpty(tui_jian.getText().toString())) {
                                        new AddReferenceId().addReferenceId(20155, result.getUserId(), tui_jian.getText().toString(), new Callback<AddReferenceId.AddReferenceIdJson>() {
                                            @Override
                                            public void onSuccess(int what, AddReferenceId.AddReferenceIdJson result) {
                                                DPLogUtil.d("getIsUseComplete onSuccess 200 getIsTermsOfUseAgreed VerifyEmailActivity");
                                                jiaSignIn();
                                            }

                                            @Override
                                            public void onError(int what, int type, String msg, Exception e) {
                                                showToast(e.getMessage());
                                            }
                                        });

                                    } else {
                                        jiaSignIn();
                                    }

                                }

                                @Override
                                public void onError(int what, int type, String msg, Exception e) {
                                    showToast(e.getMessage());
                                    hideProgressDialog();
                                }
                            });
//                    String[] names = name.getText().toString().replaceAll("\\s+"," ").split(" ");
                }

            }
        });
    }


    private void showDialog() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(getAttchedActivity()).setItems(userTypes, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                user_type_spinner.setText(userTypes[which]);
                type = userTypes[which];
            }
        });
        dialog.show();

    }

    private boolean checkSignUp() {
        if (isEmpty(name.getText().toString())) {
            showToast(R.string.base_login_sign_up_name_hint);
            return false;
        } else if (isEmpty(password_edit.getText().toString())) {
            showToast(R.string.base_login_sign_up_password_hint);
            return false;
        } else if (isEmpty(password_edit_again.getText().toString())) {
            showToast(R.string.base_login_sign_up_password_again_hint);
            return false;
        } else if (isEmpty(email.getText().toString())) {
            showToast(R.string.base_login_sign_up_email_hint);
            return false;
        } else if (isEmpty(type)) {
            showToast(R.string.sign_up_forget_select_user_type);
            return false;
        }

        return true;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onHandleMessage(Message msg) {

    }

    @Override
    public void onFragmentUpdate() {

    }

    protected static String getUsername(Session session) {
        Authentication auth = session.getAuthentication();
        return ((BasicAuthentication) auth).getUsername();
    }

    //    登录
    public void signIn(final Session session, final JSONObjectCallback callback, final SignInMethod method) {

        try {
            long companyId = Long.valueOf(LineMoneyContext.getLiferay_company_id());
            session.setCallback(callback);
            UserService userService = new UserService(session);
            String username = getUsername(session);
            if (method == SignInMethod.EMAIL) {
                userService.getUserByEmailAddress(companyId, username);
            } else if (method == SignInMethod.USER_ID) {
                userService.getUserById(Long.parseLong(username));
            } else {
                userService.getUserByScreenName(companyId, username);
            }
        } catch (Exception e) {
            callback.onFailure(e);
        }

    }

    private void signIn(final Session session, final JSONObjectCallback callback) {
        String e = getUsername(session);
        SignInMethod method = SignInMethod.fromUsername(e);
        signIn(session, callback, method);
    }

    private void jiaSignIn() {
        PasswordSaver.save(email.getText().toString(), password_edit.getText().toString());
        final Session session = new SessionImpl(LineMoneyContext.getServer(), new BasicAuthentication(email.getText().toString(), password_edit.getText().toString()));
        signIn(session, new JSONObjectCallback() {
            @Override
            public void onSuccess(JSONObject result) {
                Log.d("LineMoney", result.toString());
                session.setCallback(null);
                LineMoneyContext.setSession(session);
                LineMoneyContext.setPassword(password_edit.getText().toString());
                User user = DPGsonUtil.fromJson(result.toString(), User.class);
                LineMoneyContext.setLoggedUser(user);

                new CurrencyService().getCurrency(currencyListResultCallback);
            }

            @Override
            public void onFailure(Exception e) {
                e.printStackTrace();
//                        showToast(R.string.txt_login_failed);
                showToast(e.getMessage());
                session.setCallback(null);
            }
        });
    }
}
